<script lang="ts" setup>
import { computed, ref, watch } from 'vue';

import {
  ElButton,
  ElCard,
  ElDatePicker,
  ElForm,
  ElFormItem,
  ElInput,
  ElOption,
  ElPagination,
  ElSelect,
  ElTable,
  ElTableColumn,
} from 'element-plus';

// 图表组件
import CostCompositionPie from './CostCompositionPie.vue';
import VehicleCostBar from './VehicleCostBar.vue';

// 筛选表单数据
const searchForm = ref({
  dateRange: [] as string[],
  licensePlate: '',
});

// 日期快捷选项
const shortcuts = [
  {
    text: '本月',
    value: () => {
      const start = new Date();
      start.setDate(1);
      start.setHours(0, 0, 0, 0);
      const end = new Date();
      end.setHours(23, 59, 59, 999);
      return [start, end];
    },
  },
  {
    text: '本季度',
    value: () => {
      const start = new Date();
      const quarter = Math.floor(start.getMonth() / 3);
      start.setMonth(quarter * 3, 1);
      start.setHours(0, 0, 0, 0);
      const end = new Date();
      end.setMonth((quarter + 1) * 3, 0);
      end.setHours(23, 59, 59, 999);
      return [start, end];
    },
  },
  {
    text: '本年',
    value: () => {
      const start = new Date();
      start.setMonth(0, 1);
      start.setHours(0, 0, 0, 0);
      const end = new Date();
      end.setMonth(11, 31);
      end.setHours(23, 59, 59, 999);
      return [start, end];
    },
  },
];

// Mock统计数据
const statisticsData = ref({
  totalMaintenanceCost: 12_500, // 总维保成本（元）
  totalEstimatedFuelCost: 8925, // 预估燃油总成本（元）
  averageCostPerVehicle: 2142.5, // 单车平均成本（元）
});

// Mock成本构成数据
const costDistribution = ref({
  maintenanceRatio: 58, // 维保成本占比
  fuelRatio: 42, // 燃油成本占比
});

// Mock单车成本对比数据
const vehicleCostData = ref([
  {
    licensePlate: '京A12345',
    totalCost: 2850,
    maintenanceCost: 1200,
    estimatedFuelCost: 1650,
  },
  {
    licensePlate: '京B67890',
    totalCost: 2450,
    maintenanceCost: 800,
    estimatedFuelCost: 1650,
  },
  {
    licensePlate: '京C11111',
    totalCost: 2650,
    maintenanceCost: 1500,
    estimatedFuelCost: 1150,
  },
  {
    licensePlate: '京D22222',
    totalCost: 3100,
    maintenanceCost: 2000,
    estimatedFuelCost: 1100,
  },
  {
    licensePlate: '京E33333',
    totalCost: 2200,
    maintenanceCost: 900,
    estimatedFuelCost: 1300,
  },
  {
    licensePlate: '京F44444',
    totalCost: 2900,
    maintenanceCost: 1800,
    estimatedFuelCost: 1100,
  },
  {
    licensePlate: '京G55555',
    totalCost: 2100,
    maintenanceCost: 1100,
    estimatedFuelCost: 1000,
  },
  {
    licensePlate: '京H66666',
    totalCost: 2750,
    maintenanceCost: 1600,
    estimatedFuelCost: 1150,
  },
  {
    licensePlate: '京I77777',
    totalCost: 2300,
    maintenanceCost: 1300,
    estimatedFuelCost: 1000,
  },
  {
    licensePlate: '京J88888',
    totalCost: 2050,
    maintenanceCost: 950,
    estimatedFuelCost: 1100,
  },
]);

// Mock数据明细
const tableData = ref([
  {
    id: 1,
    licensePlate: '京A12345',
    totalMileage: 15_600,
    maintenanceCount: 2,
    maintenanceCost: 1200,
    estimatedFuelCost: 1650,
  },
  {
    id: 2,
    licensePlate: '京B67890',
    totalMileage: 14_200,
    maintenanceCount: 1,
    maintenanceCost: 800,
    estimatedFuelCost: 1650,
  },
  {
    id: 3,
    licensePlate: '京C11111',
    totalMileage: 13_800,
    maintenanceCount: 3,
    maintenanceCost: 1500,
    estimatedFuelCost: 1150,
  },
  {
    id: 4,
    licensePlate: '京D22222',
    totalMileage: 12_500,
    maintenanceCount: 2,
    maintenanceCost: 2000,
    estimatedFuelCost: 1100,
  },
  {
    id: 5,
    licensePlate: '京E33333',
    totalMileage: 11_900,
    maintenanceCount: 1,
    maintenanceCost: 900,
    estimatedFuelCost: 1300,
  },
  {
    id: 6,
    licensePlate: '京F44444',
    totalMileage: 10_800,
    maintenanceCount: 2,
    maintenanceCost: 1800,
    estimatedFuelCost: 1100,
  },
  {
    id: 7,
    licensePlate: '京G55555',
    totalMileage: 9600,
    maintenanceCount: 1,
    maintenanceCost: 1100,
    estimatedFuelCost: 1000,
  },
  {
    id: 8,
    licensePlate: '京H66666',
    totalMileage: 8900,
    maintenanceCount: 2,
    maintenanceCost: 1600,
    estimatedFuelCost: 1150,
  },
  {
    id: 9,
    licensePlate: '京I77777',
    totalMileage: 8200,
    maintenanceCount: 2,
    maintenanceCost: 1300,
    estimatedFuelCost: 1000,
  },
  {
    id: 10,
    licensePlate: '京J88888',
    totalMileage: 7500,
    maintenanceCount: 1,
    maintenanceCost: 950,
    estimatedFuelCost: 1100,
  },
]);

// 分页配置
const pagination = ref({
  currentPage: 1,
  pageSize: 20,
  total: tableData.value.length,
});

// 每页条数选项
const pageSizeOptions = [15, 20, 25, 30];

// 筛选后的数据（未分页）
const filteredTableData = computed(() => {
  let data = tableData.value;

  // 按车牌号模糊搜索
  if (searchForm.value.licensePlate) {
    const keyword = searchForm.value.licensePlate.toLowerCase();
    data = data.filter((record) =>
      record.licensePlate.toLowerCase().includes(keyword),
    );
  }

  return data;
});

// 分页后的数据
const paginatedTableData = computed(() => {
  const start = (pagination.value.currentPage - 1) * pagination.value.pageSize;
  const end = start + pagination.value.pageSize;
  return filteredTableData.value.slice(start, end);
});

// 计算属性 - 数据概览卡片
const overviewCards = computed(() => [
  {
    title: '总维保成本',
    value: statisticsData.value.totalMaintenanceCost.toLocaleString(),
    unit: '元',
    icon: '🔧',
    color: 'bg-blue-500',
  },
  {
    title: '预估燃油总成本',
    value: statisticsData.value.totalEstimatedFuelCost.toLocaleString(),
    unit: '元',
    icon: '⛽',
    color: 'bg-green-500',
  },
  {
    title: '单车平均成本',
    value: statisticsData.value.averageCostPerVehicle.toFixed(1),
    unit: '元',
    icon: '📊',
    color: 'bg-purple-500',
  },
]);

// 监听筛选条件变化，更新数据
watch(
  () => searchForm.value,
  () => {
    updatePagination();
  },
  { deep: true },
);

// 处理查询
const handleSearch = () => {
  // 筛选逻辑已经在computed中处理
};

// 处理重置
const handleReset = () => {
  searchForm.value = {
    dateRange: [],
    licensePlate: '',
  };
  handleSearch();
};

// 处理导出
const handleExport = () => {
  // 获取当前日期用于文件名
  const today = new Date();
  const dateStr = today.toISOString().slice(0, 10).replaceAll('-', '');

  // 准备导出数据
  const exportData = filteredTableData.value.map((record) => ({
    车牌号: record.licensePlate,
    总里程: `${record.totalMileage} 公里`,
    维保次数: `${record.maintenanceCount} 次`,
    维保总费用: `${record.maintenanceCost} 元`,
    预估燃油费: `${record.estimatedFuelCost} 元`,
  }));

  // 创建CSV内容
  const headers = ['车牌号', '总里程', '维保次数', '维保总费用', '预估燃油费'];
  const csvContent = [
    headers.join(','),
    ...exportData.map((row) => {
      const rowValues = [
        row.车牌号,
        row.总里程,
        row.维保次数,
        row.维保总费用,
        row.预估燃油费,
      ];
      return rowValues
        .map((value) => {
          // 如果值包含逗号，用双引号包围
          return value && value.toString().includes(',')
            ? `"${value}"`
            : value || '';
        })
        .join(',');
    }),
  ].join('\n');

  // 创建下载链接
  const blob = new Blob([`\uFEFF${csvContent}`], {
    type: 'text/csv;charset=utf-8;',
  });
  const link = document.createElement('a');
  const url = URL.createObjectURL(blob);
  link.setAttribute('href', url);
  link.setAttribute('download', `车辆成本分析报表_${dateStr}.csv`);
  link.style.visibility = 'hidden';
  document.body.append(link);
  link.click();
  link.remove();
};

// 处理分页变化
const handlePageChange = (page: number) => {
  pagination.value.currentPage = page;
};

// 处理每页条数变化
const handlePageSizeChange = (size: number) => {
  pagination.value.pageSize = size;
  pagination.value.currentPage = 1; // 切换条数时重置到第一页
};

// 更新分页总数
const updatePagination = () => {
  pagination.value.total = filteredTableData.value.length;
  pagination.value.currentPage = 1; // 重置到第一页
};

// 处理排序
const handleSort = (_column: any) => {
  // 排序功能待实现
};
</script>

<template>
  <div class="min-h-screen bg-gray-50 p-5">
    <!-- 筛选区域 -->
    <ElCard class="mb-5 rounded-xl border-0 shadow-lg">
      <ElForm :model="searchForm" :inline="true" class="search-form">
        <div class="flex flex-wrap items-center gap-4">
          <ElFormItem
            label="日期范围"
            prop="dateRange"
            class="min-w-[200px] flex-1"
          >
            <ElDatePicker
              v-model="searchForm.dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              :shortcuts="shortcuts"
              class="w-full"
            />
          </ElFormItem>

          <ElFormItem
            label="车牌号"
            prop="licensePlate"
            class="min-w-[150px] flex-1"
          >
            <ElInput
              v-model="searchForm.licensePlate"
              placeholder="请输入车牌号"
              clearable
              @keyup.enter="handleSearch"
              class="w-full"
            />
          </ElFormItem>

          <div class="flex gap-2">
            <ElButton type="primary" @click="handleSearch" class="px-4">
              查询
            </ElButton>
            <ElButton @click="handleReset" class="px-4"> 重置 </ElButton>
            <ElButton type="success" @click="handleExport" class="px-4">
              导出
            </ElButton>
          </div>
        </div>
      </ElForm>
    </ElCard>

    <!-- 数据概览区 -->
    <div class="mb-5 grid grid-cols-1 gap-4 md:grid-cols-3">
      <ElCard
        v-for="card in overviewCards"
        :key="card.title"
        class="rounded-xl border-0 shadow-lg transition-shadow duration-300 hover:shadow-xl"
      >
        <div class="flex items-center justify-between">
          <div>
            <p class="mb-1 text-sm text-gray-600">{{ card.title }}</p>
            <p class="text-2xl font-bold text-gray-800">
              {{ card.value }}
              <span v-if="card.unit" class="ml-1 text-sm text-gray-500">{{
                card.unit
              }}</span>
            </p>
          </div>
          <div :class="`rounded-lg p-3 text-3xl ${card.color} text-white`">
            {{ card.icon }}
          </div>
        </div>
      </ElCard>
    </div>

    <!-- 图表展示区 -->
    <div class="mb-5 grid grid-cols-1 gap-5 lg:grid-cols-2">
      <!-- 成本构成（饼图） -->
      <ElCard class="rounded-xl border-0 shadow-lg">
        <div class="p-4">
          <h3 class="mb-4 text-lg font-semibold text-gray-800">成本构成占比</h3>
          <div class="h-64">
            <CostCompositionPie :data="costDistribution" />
          </div>
        </div>
      </ElCard>

      <!-- 单车成本对比（柱状图） -->
      <ElCard class="rounded-xl border-0 shadow-lg">
        <div class="p-4">
          <h3 class="mb-4 text-lg font-semibold text-gray-800">
            单车总运营成本对比
          </h3>
          <div class="h-64">
            <VehicleCostBar :data="vehicleCostData" />
          </div>
        </div>
      </ElCard>
    </div>

    <!-- 数据明细区 -->
    <ElCard class="rounded-xl border-0 shadow-lg">
      <div class="p-4">
        <h3 class="mb-4 text-lg font-semibold text-gray-800">单车成本明细</h3>
        <ElTable
          :data="paginatedTableData"
          class="cost-table overflow-hidden rounded-lg"
          :header-cell-style="{
            background: '#f8fafc',
            color: '#374151',
            fontWeight: '600',
            borderBottom: '2px solid #e5e7eb',
          }"
          :cell-style="{ borderBottom: '1px solid #f1f5f9' }"
          @sort-change="handleSort"
        >
          <ElTableColumn type="index" label="序号" width="60" align="center">
            <template #default="{ $index }">
              <span class="font-medium text-gray-500">{{ $index + 1 }}</span>
            </template>
          </ElTableColumn>
          <ElTableColumn
            prop="licensePlate"
            label="车牌号"
            sortable
            width="120"
            align="center"
          />
          <ElTableColumn
            prop="totalMileage"
            label="总里程"
            sortable
            width="120"
            align="center"
          >
            <template #default="{ row }">
              {{ row.totalMileage }} 公里
            </template>
          </ElTableColumn>
          <ElTableColumn
            prop="maintenanceCount"
            label="维保次数"
            sortable
            width="100"
            align="center"
          />
          <ElTableColumn
            prop="maintenanceCost"
            label="维保总费用"
            sortable
            width="120"
            align="center"
          >
            <template #default="{ row }">
              {{ row.maintenanceCost }} 元
            </template>
          </ElTableColumn>
          <ElTableColumn
            prop="estimatedFuelCost"
            label="预估燃油费"
            sortable
            width="120"
            align="center"
          >
            <template #default="{ row }">
              {{ row.estimatedFuelCost }} 元
            </template>
          </ElTableColumn>
        </ElTable>

        <!-- 分页 -->
        <div class="mt-4 flex items-center justify-between">
          <div class="flex items-center gap-4">
            <span class="text-sm text-gray-600">
              显示
              {{ (pagination.currentPage - 1) * pagination.pageSize + 1 }} 到
              {{
                Math.min(
                  pagination.currentPage * pagination.pageSize,
                  pagination.total,
                )
              }}
              条，共 {{ pagination.total }} 条
            </span>
            <ElSelect
              v-model="pagination.pageSize"
              @change="handlePageSizeChange"
              class="w-20"
              size="small"
            >
              <ElOption
                v-for="size in pageSizeOptions"
                :key="size"
                :label="`${size} 条/页`"
                :value="size"
              />
            </ElSelect>
          </div>
          <ElPagination
            v-model:current-page="pagination.currentPage"
            :page-size="pagination.pageSize"
            :total="pagination.total"
            @current-change="handlePageChange"
            layout="prev, pager, next, jumper"
            background
          />
        </div>
      </div>
    </ElCard>
  </div>
</template>

<style scoped>
/* 响应式优化 */
@media (max-width: 768px) {
  .flex-wrap {
    flex-direction: column;
    align-items: stretch;
  }

  .grid-cols-3 {
    grid-template-columns: repeat(1, 1fr);
  }

  .grid-cols-2 {
    grid-template-columns: 1fr;
  }
}

.chart-container {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 16px;
  background: #f8fafc;
  border-radius: 8px;
}

.pie-chart {
  position: relative;
}

.pie-chart svg {
  transform: rotate(-90deg);
}

.bar-chart {
  min-width: 400px;
}

.bar-item {
  flex: 1;
  min-width: 60px;
}

.bar {
  width: 40px;
  cursor: pointer;
  background: linear-gradient(to top, #8b5cf6, #a78bfa);
  border-radius: 4px 4px 0 0;
  transition: all 0.3s ease;
}

.bar:hover {
  box-shadow: 0 4px 8px rgb(139 92 246 / 30%);
  transform: scaleY(1.1);
}

:deep(.cost-table) {
  overflow: hidden;
  background: #fff;
  border-radius: 12px;
  box-shadow:
    0 4px 6px -1px rgb(0 0 0 / 10%),
    0 2px 4px -1px rgb(0 0 0 / 6%);
}

:deep(.cost-table .el-table__header-wrapper) {
  border-radius: 12px 12px 0 0;
}

:deep(.cost-table .el-table__body-wrapper) {
  border-radius: 0 0 12px 12px;
}

:deep(.cost-table .el-table__row:nth-child(even)) {
  background-color: #f9fafb;
}

/* 自定义样式 */
:deep(.search-form .el-form-item__label) {
  font-size: 14px;
  font-weight: 500;
  color: #374151;
}

:deep(.el-input__wrapper) {
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 1px 2px 0 rgb(0 0 0 / 5%);
  transition: all 0.2s ease;
}

:deep(.el-select__wrapper) {
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 1px 2px 0 rgb(0 0 0 / 5%);
  transition: all 0.2s ease;
}

:deep(.el-button) {
  font-weight: 500;
  border-radius: 8px;
  transition: all 0.2s ease;
}

:deep(.el-card) {
  border: 1px solid #e5e7eb;
  border-radius: 12px;
  transition: all 0.3s ease;
}

:deep(.el-table) {
  overflow: hidden;
  border-radius: 8px;
}

:deep(.el-pagination) {
  justify-content: flex-end;
}

/* 图表容器样式 */

/* 自定义表格样式 */
</style>
